package com.ruoyi.web.controller.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.UploadConstants;
import com.ruoyi.common.constant.WechatConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.entity.BO.wechat.AuthedAppletBO;
import com.ruoyi.common.entity.DO.wechat.ShopAppletCommitDO;
import com.ruoyi.common.entity.DO.wechat.ShopAppletSubmitAuditDO;
import com.ruoyi.common.entity.VO.shop.ShopAppletSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopAppletVO;
import com.ruoyi.common.entity.VO.shop.ShopVO;
import com.ruoyi.common.entity.VO.wechat.ShopAppletCommitSearchVO;
import com.ruoyi.common.entity.VO.wechat.ShopAppletCommitVO;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.web.controller.shop.mapper.IBackShopAppletCommitMapper;
import com.ruoyi.web.controller.shop.mapper.IBackShopAppletMapper;
import com.ruoyi.web.controller.shop.mapper.IBackShopAppletSubmitAuditMapper;
import com.ruoyi.web.controller.shop.service.IBackShopAppletCommitService;
import com.ruoyi.web.controller.shop.service.IBackShopAppletService;
import com.ruoyi.web.controller.shop.service.IBackShopService;
import com.ruoyi.web.controller.wechat.service.Impl.WechatOpenServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.bean.WxOpenMaCodeTemplate;
import me.chanjar.weixin.open.bean.ma.WxOpenMaSubmitAudit;
import me.chanjar.weixin.open.bean.ma.privacy.PrivacyOwnerSetting;
import me.chanjar.weixin.open.bean.ma.privacy.SetPrivacySetting;
import me.chanjar.weixin.open.bean.message.WxOpenMaSubmitAuditMessage;
import me.chanjar.weixin.open.bean.result.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 微信开发管理
 */
@Controller
@RequestMapping("/back/wechatOpen")
public class BackWechatOpenController extends BaseController {
    private String prefix = "wxopen";

    @Value("${wx.open.host}")
    private String openHost;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    protected WechatOpenServiceImpl wxOpenService;

    @Resource
    protected IBackShopService shopService;

    @Resource
    protected IBackShopAppletCommitService shopAppletCommitService;

    @Resource
    protected IBackShopAppletCommitMapper shopAppletCommitMapper;

    @Resource
    protected IBackShopAppletSubmitAuditMapper shopAppletSubmitAuditMapper;

    @Resource
    protected IBackShopAppletService backShopAppletService;

    @Resource
    protected IBackShopAppletMapper shopAppletMapper;

    @GetMapping("/index")
    public String index() {
        return prefix + "/index";
    }

    @RequiresPermissions("back:wechatOpen:authList")
    @GetMapping("/authList")
    public String authList() {
        return prefix + "/authList";
    }

    @RequiresPermissions("back:wechatOpen:authInfo")
    @GetMapping("/authInfo/{appId}")
    public String authInfo(@PathVariable("appId") String appId, ModelMap mmap) {
        WxOpenAuthorizerInfoResult authInfo = new WxOpenAuthorizerInfoResult();
        try {
            authInfo = wxOpenService.getWxOpenComponentService().getAuthorizerInfo(appId);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        mmap.put("authInfo", authInfo.getAuthorizerInfo());
        mmap.put("appId", appId);
        return prefix + "/authInfo";
    }

    @RequiresPermissions("back:wechatOpen:templateDraftList")
    @GetMapping("/templateDraftList")
    public String templateDraftList() {
        return prefix + "/templateDraftList";
    }

    @RequiresPermissions("back:wechatOpen:templateList")
    @GetMapping("/templateList")
    public String templateList() {
        return prefix + "/templateList";
    }

    @RequiresPermissions("back:wechatOpen:commitList")
    @GetMapping("/commitList")
    public String commitList() {
        return prefix + "/commitList";
    }

    @RequiresPermissions("back:wechatOpen:commit")
    @GetMapping("/commit/{appId}")
    public String commit(@PathVariable("appId") String appId, ModelMap mmap, HttpServletResponse response) {
        WxFastMaAccountBasicInfoResult appletInfo = wxOpenService.getAppletInfo(appId);
        if (null == appletInfo) {
            String url = "http://" + openHost + "/back/wechatOpen/auth";
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mmap.put("appletInfo", appletInfo);
        return prefix + "/commit";
    }

    @RequiresPermissions("back:wechatOpen:submitAudit")
    @GetMapping("/submitAudit/{commitId}")
    public String submitAudit(@PathVariable("commitId") Long commitId, ModelMap mmap, HttpServletResponse response) {
        ShopAppletCommitDO commitInfo = shopAppletCommitMapper.selectByPrimaryKey(commitId);
        if (null == commitInfo) {
            String url = "http://" + openHost + "/back/wechatOpen/auth";
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            WxFastMaAccountBasicInfoResult appletInfo = wxOpenService.getAppletInfo(commitInfo.getAppletAppId());
            mmap.put("commitInfo", commitInfo);
            mmap.put("appletInfo", appletInfo);
            return prefix + "/submitAudit";
        }
    }

    @GetMapping("/auth")
    public void gotoPreAuthUrl(HttpServletResponse response) {
        String host = openHost;
        String url = "http://" + host + "/back/wechatOpen/authJump";
        try {
            url = wxOpenService.getWxOpenComponentService().getPreAuthUrl(url);
            // 添加来源，解决302跳转来源丢失的问题
            response.addHeader("Referer", "http://" + host);
            response.sendRedirect(url);
        } catch (WxErrorException | IOException e) {
            logger.error("gotoPreAuthUrl", e);
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/authJump")
    @ResponseBody
    public Object authJump(@RequestParam("auth_code") String authorizationCode, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        try {
            WxOpenQueryAuthResult queryAuthResult = wxOpenService.getWxOpenComponentService().getQueryAuth(authorizationCode);
            if (null != queryAuthResult && null != queryAuthResult.getAuthorizationInfo()) {
                logger.info("getQueryAuth", queryAuthResult);
                modelAndView.setViewName("authsuccess");
            } else {
                modelAndView.addObject("errorMessage", "授权失败！原因：未知");
                modelAndView.setViewName("error/business");
            }
        } catch (WxErrorException e) {
            logger.error("gotoPreAuthUrl", e);
            modelAndView.addObject("errorMessage", e.getMessage());
            modelAndView.setViewName("error/business");
        }
        return modelAndView;
    }

    @RequiresPermissions("back:wechatOpen:commit")
    @PostMapping("/commit")
    @ResponseBody
    @Transactional
    public AjaxResult commit(ShopAppletCommitDO shopAppletCommitDO) {
        if (null == shopAppletCommitDO.getTemplateId()) {
            return error("请选择代码模板！");
        }
        if (StringUtils.isEmpty(shopAppletCommitDO.getAppletAppId())) {
            return error("所选小程序未授权！");
        }
        shopAppletCommitDO.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        shopAppletCommitDO.setCreateTime(new Date());
        shopAppletCommitDO.setStatus(0);
        ShopVO shopInfo = shopService.getShopInfoByAppId(shopAppletCommitDO.getAppletAppId());
        if (null == shopInfo) {
            return error("该小程序未绑定店铺！");
        }
        if (1 != shopInfo.getReviewStatus()) {
            return error("该小程序绑定的店铺未审核通过！");
        }
        int auditingCount = shopAppletCommitMapper.countAuditingCommit(shopAppletCommitDO.getAppletAppId());
        if (0 != auditingCount) {
            return error("该小程序正在审核中！");
        }
        shopAppletCommitDO.setShopId(shopInfo.getId());
        JSONObject jsonObject = new JSONObject();
        JSONObject extJsonObject = new JSONObject();
        JSONObject windowJsonObject = new JSONObject();
        jsonObject.put("extAppid", shopAppletCommitDO.getAppletAppId());
        extJsonObject.put("navigationBarTitleText", shopInfo.getShopName());
        extJsonObject.put("appid", shopAppletCommitDO.getAppletAppId());
        windowJsonObject.put("navigationBarTitleText", shopInfo.getShopName());
        jsonObject.put("window", windowJsonObject);
        jsonObject.put("ext", extJsonObject);
        WxOpenResult result = wxOpenService.codeCommit(shopAppletCommitDO, jsonObject);
        if (null != result && !result.isSuccess()) {
            return error(result.getErrmsg());
        }
        shopAppletCommitDO.setExtJson(JSON.toJSONString(jsonObject));
        MultipartFile demoQrCodeFile = wxOpenService.getDemoQrCode(shopAppletCommitDO.getAppletAppId(), "", new HashMap<>());
        try {
            String filePath = FileUploadUtils.upload(UploadConstants.ModelTypeEnum.SHOP_APPLET_DEMO.getUploadPath(), demoQrCodeFile, MimeTypeUtils.IMAGE_EXTENSION);
            shopAppletCommitDO.setDemoQrCode(filePath);
        } catch (IOException | InvalidExtensionException e) {
            e.printStackTrace();
        }
        shopAppletCommitMapper.deleteForCommitByAppId(shopAppletCommitDO.getAppletAppId());
        shopAppletCommitMapper.insertSelective(shopAppletCommitDO);
        return success();
    }

    @RequiresPermissions("back:wechatOpen:submitAudit")
    @PostMapping("/submitAudit")
    @ResponseBody
    public AjaxResult submitAudit(ShopAppletSubmitAuditDO shopAppletSubmitAuditDO) {
        if (null == shopAppletSubmitAuditDO.getCommitId()) {
            return error("请生成体验版后再提交！");
        }
        ShopAppletCommitDO shopAppletCommitDO = shopAppletCommitMapper.selectByPrimaryKey(shopAppletSubmitAuditDO.getCommitId());
        if (null == shopAppletCommitDO) {
            return error("请生成体验版后再提交！");
        }
        shopAppletSubmitAuditDO.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        shopAppletSubmitAuditDO.setCreateTime(new Date());
        shopAppletSubmitAuditDO.setStatus(WechatConstants.AuditStatusEnum.AUDITING.getValue());
        //设置审核类目
        WxOpenMaSubmitAuditMessage wxOpenMaSubmitAuditMessage = new WxOpenMaSubmitAuditMessage();
        WxFastMaBeenSetCategoryResult categoryResult = wxOpenService.getCategory(shopAppletCommitDO.getAppletAppId());
        if (!"0".equals(categoryResult.getErrcode())) {
            return error(categoryResult.getErrmsg());
        }
        List<WxFastMaBeenSetCategoryResult.CategoriesBean> categories = categoryResult.getCategories();
        List<WxOpenMaSubmitAudit> itemList = new ArrayList<>();
        for (WxFastMaBeenSetCategoryResult.CategoriesBean one : categories
        ) {
            WxOpenMaSubmitAudit item = new WxOpenMaSubmitAudit();
            item.setFirstId(one.getFirst());
            item.setSecondId(one.getSecond());
            item.setFirstClass(one.getFirstName());
            item.setSecondClass(one.getSecondName());
            itemList.add(item);
        }
        wxOpenMaSubmitAuditMessage.setItemList(itemList);
        //设置小程序用户隐私保护指引
        SetPrivacySetting dto = new SetPrivacySetting();
        PrivacyOwnerSetting pos = new PrivacyOwnerSetting();
        pos.setContactPhone("18948380564");
        pos.setNoticeMethod("通过弹窗或者公告或者其他方式");
        dto.setOwnerSetting(pos);
        List<SetPrivacySetting.Setting> settingList = new ArrayList<>();
        settingList.add(new SetPrivacySetting.Setting("AlbumWriteOnly", "保存商品海报"));
        settingList.add(new SetPrivacySetting.Setting("Location", "自动填入收货地址"));
        settingList.add(new SetPrivacySetting.Setting("PhoneNumber", "购物流程"));
        settingList.add(new SetPrivacySetting.Setting("UserInfo", "购物流程"));
        settingList.add(new SetPrivacySetting.Setting("Album", "转发分享商品海报"));
        settingList.add(new SetPrivacySetting.Setting("MessageFile", "商品分享"));
        dto.setSettingList(settingList);
        wxOpenService.setPrivacySetting(shopAppletCommitDO.getAppletAppId(), dto);
        WxOpenMaSubmitAuditResult result = wxOpenService.submitAudit(shopAppletCommitDO.getAppletAppId(), wxOpenMaSubmitAuditMessage);
        if (null != result && !result.isSuccess()) {
            return error(result.getErrmsg());
        }
        shopAppletSubmitAuditDO.setAuditid(result.getAuditId());
        shopAppletSubmitAuditMapper.insertSelective(shopAppletSubmitAuditDO);
        shopAppletCommitDO.setStatus(WechatConstants.CommitStatusEnum.AUDITING.getValue());
        shopAppletCommitMapper.updateByPrimaryKeySelective(shopAppletCommitDO);
        shopAppletMapper.updateReviewStatusByAppId(shopAppletCommitDO.getAppletAppId(), WechatConstants.ReviewStatusEnum.AUDITING.getValue());
        return success();
    }

    @RequiresPermissions("back:wechatOpen:rollbackAudit")
    @PostMapping("/rollbackAudit")
    @ResponseBody
    public AjaxResult rollbackAudit(ShopAppletCommitDO shopAppletCommitDO) {
        wxOpenService.rollbackAudit(shopAppletCommitDO.getAppletAppId());
        shopAppletMapper.updateReviewStatusByAppId(shopAppletCommitDO.getAppletAppId(), WechatConstants.ReviewStatusEnum.PASS.getValue());
        return success();
    }

    @RequiresPermissions("back:wechatOpen:releaseAudit")
    @PostMapping("/releaseAudit")
    @ResponseBody
    public AjaxResult releaseAudit(ShopAppletCommitDO shopAppletCommitDO) {
        wxOpenService.releaseAudited(shopAppletCommitDO.getAppletAppId());
        shopAppletCommitMapper.releaseByAppId(shopAppletCommitDO.getAppletAppId());
        //自动覆盖域名
        AjaxResult result = this.autoSetDomain(shopAppletCommitDO);
        if (!"0".equals(result.get("code"))) {
            return success("发布成功，但域名配置失败，请查看授权信息自动配置域名！");
        }
        return success("发布成功！");
    }

    @RequiresPermissions("back:wechatOpen:modifyDomain")
    @PostMapping("/modifyDomain/{action}")
    @ResponseBody
    public AjaxResult modifyDomain(@PathVariable("action") String action) {
        return error();
    }

    @RequiresPermissions("back:wechatOpen:modifyDomain")
    @PostMapping("/autoSetDomain")
    @ResponseBody
    public AjaxResult autoSetDomain(ShopAppletCommitDO shopAppletCommitDO) {
        if (shopAppletCommitDO.getAppletAppId() == null) {
            return error("设置失败！");
        }
        HashMap<String, List<String>> domains = new HashMap<>();
        domains.put("requestdomain", Arrays.asList("https://gl.xrmwl.com", "https://img.xrmwl.com", "https://xrmwl.com"));
        domains.put("wsrequestdomain", Arrays.asList("wss://gl.xrmwl.com", "wss://img.xrmwl.com", "wss://xrmwl.com"));
        domains.put("uploaddomain", Arrays.asList("https://gl.xrmwl.com", "https://img.xrmwl.com", "https://xrmwl.com"));
        domains.put("downloaddomain", Arrays.asList("https://gl.xrmwl.com", "https://img.xrmwl.com", "https://xrmwl.com"));
        WxOpenMaDomainResult result = wxOpenService.modifyDomain(shopAppletCommitDO.getAppletAppId(), "set", domains);
        if (!result.isSuccess()) {
            return error(result.getErrmsg());
        }
        return success();
    }

    @RequiresPermissions("back:wechatOpen:speedupAudit")
    @PostMapping("/speedupAudit")
    @ResponseBody
    public AjaxResult speedupAudit(AuthedAppletBO authedAppletBO) {
        wxOpenService.speedupAudit(authedAppletBO.getAppId(), authedAppletBO.getAuditid());
        return success("加急成功！");
    }


    @RequiresPermissions("back:wechatOpen:back")
    @PostMapping("/backLatest")
    @ResponseBody
    public AjaxResult backLatest(AuthedAppletBO authedAppletBO) {
        WxOpenResult result = wxOpenService.backLatest(authedAppletBO.getAppId());
        if (null != result && !result.isSuccess()) {
            return error(result.getErrmsg());
        }
        shopAppletCommitMapper.backLatestByAppId(authedAppletBO.getAppId());
        return success("回退上一版本成功！");
    }

    @GetMapping("/get_authorizer_info")
    @ResponseBody
    public WxOpenAuthorizerInfoResult getAuthorizerInfo(@RequestParam String appId) {
        try {
            return wxOpenService.getWxOpenComponentService().getAuthorizerInfo(appId);
        } catch (WxErrorException e) {
            logger.error("getAuthorizerInfo", e);
            throw new RuntimeException(e);
        }
    }

    @RequiresPermissions("back:wechatOpen:commitList")
    @PostMapping("/commitList")
    @ResponseBody
    public TableDataInfo commitList(ShopAppletCommitSearchVO shopAppletCommitSearchVO) {
        startPage();
        List<ShopAppletCommitVO> list = shopAppletCommitService.searchList(shopAppletCommitSearchVO);
        if (list.size() > 0) {
            for (ShopAppletCommitVO one : list
            ) {
                if (WechatConstants.CommitStatusEnum.PRE_CHECK.getValue() == one.getStatus()) {
                    //待检测的提交
                    WxOpenResult result = wxOpenService.getCodePrivacyInfo(one.getAppletAppId());
                    if (null != result && result.isSuccess()) {
                        one.setStatus(WechatConstants.CommitStatusEnum.PRE_COMMIT.getValue());
                        shopAppletCommitMapper.updateStatusById(one.getId(), one.getStatus());
                    }
                } else if (WechatConstants.CommitStatusEnum.AUDITING.getValue() == one.getStatus()) {
                }
            }
        }
        return getDataTable(list);
    }

    @RequiresPermissions("back:wechatOpen:authList")
    @PostMapping("/searchAuthList")
    @ResponseBody
    public TableDataInfo searchAuthList() {
        ShopAppletSearchVO searchVO = new ShopAppletSearchVO();
        searchVO.setIsDelete(0);
        searchVO.setIsEnable(1);
        searchVO.setIsAuth(1);
        List<ShopAppletVO> resultList = backShopAppletService.searchList(searchVO);
        List<AuthedAppletBO> authList = new ArrayList<>();
        for (ShopAppletVO appletInfo : resultList
        ) {
            AuthedAppletBO authedAppletBO = shopAppletMapper.getShopAppletAuthInfoById(appletInfo.getAppletAppId());
            if (null != authedAppletBO) {
                if (null == authedAppletBO.getCommitId()) {
                    authedAppletBO.setStatus(-1);
                }
                if (null != authedAppletBO.getStatus()) {
                    if (WechatConstants.CommitStatusEnum.PRE_CHECK.getValue() == authedAppletBO.getStatus()) {
                        //待检测的提交
                        WxOpenResult result = wxOpenService.getCodePrivacyInfo(authedAppletBO.getAppId());
                        if (null != result && result.isSuccess()) {
                            authedAppletBO.setStatus(WechatConstants.CommitStatusEnum.PRE_COMMIT.getValue());
                            shopAppletCommitMapper.updateStatusById(authedAppletBO.getCommitId(), authedAppletBO.getStatus());
                        }
                    } else if (null != authedAppletBO.getAuditid() &&
                            WechatConstants.CommitStatusEnum.PRE_COMMIT.getValue() != authedAppletBO.getStatus() &&
                            WechatConstants.CommitStatusEnum.RELEASE.getValue() != authedAppletBO.getStatus()
                    ) {
                        //审核中
                        WxOpenMaQueryAuditResult result = wxOpenService.getAuditResult(authedAppletBO.getAppId(), authedAppletBO.getAuditid());
                        if (null != result && result.isSuccess()) {
                            switch (WechatConstants.AuditStatusEnum.match(result.getStatus())) {
                                case PASS:
                                    authedAppletBO.setStatus(WechatConstants.CommitStatusEnum.PASS.getValue());
                                    shopAppletMapper.updateReviewStatusByAppId(authedAppletBO.getAppId(), WechatConstants.ReviewStatusEnum.PASS.getValue());
                                    break;
                                case REJECT:
                                    authedAppletBO.setStatus(WechatConstants.CommitStatusEnum.REJECT.getValue());
                                    shopAppletMapper.updateReviewStatusByAppId(authedAppletBO.getAppId(), WechatConstants.ReviewStatusEnum.PASS.getValue());
                                    authedAppletBO.setStatusDesc(result.getReason());
                                    break;
                                case ROLLBACK:
                                    authedAppletBO.setStatus(WechatConstants.CommitStatusEnum.ROLLBACK.getValue());
                                    shopAppletMapper.updateReviewStatusByAppId(authedAppletBO.getAppId(), WechatConstants.ReviewStatusEnum.PASS.getValue());
                                    break;
                                default:
                                    break;
                            }
                            shopAppletCommitMapper.updateStatusById(authedAppletBO.getCommitId(), authedAppletBO.getStatus());
                            shopAppletSubmitAuditMapper.updateStatusByAuditid(result.getAuditId(), result.getStatus());
                        }
                    }
                    authList.add(authedAppletBO);
                }
            }

        }
        return getDataTable(authList);
    }

    @RequiresPermissions("back:wechatOpen:templateDraftList")
    @PostMapping("/searchTemplateDraftList")
    @ResponseBody
    public TableDataInfo searchTemplateDraftList() {
        List<WxOpenMaCodeTemplate> templateDraftList;
        try {
            templateDraftList = wxOpenService.getWxOpenComponentService().getTemplateDraftList();
            if (templateDraftList.size() > 0) {
                //按时间排序
                templateDraftList.sort((o1, o2) -> {
                    long diff = o1.getCreateTime() - o2.getCreateTime();
                    if (diff > 0) {
                        return -1;
                    } else {
                        return 1;
                    }
                });
            }

            return getDataTable(templateDraftList);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return getDataTable(new ArrayList<>());
    }

    @RequiresPermissions("back:wechatOpen:templateList")
    @PostMapping("/searchTemplateList")
    @ResponseBody
    public TableDataInfo searchTemplateList(Integer templateType) {
        List<WxOpenMaCodeTemplate> templateList;
        try {
            templateList = wxOpenService.getWxOpenComponentService().getTemplateList(templateType);
            if (templateList.size() > 0) {
                //按时间排序
                templateList.sort((o1, o2) -> {
                    long diff = o1.getCreateTime() - o2.getCreateTime();
                    if (diff > 0) {
                        return -1;
                    } else {
                        return 1;
                    }
                });
            }
            return getDataTable(templateList);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return getDataTable(new ArrayList<>());
    }

    @RequiresPermissions("back:wechatOpen:addToTemplate")
    @PostMapping("/addToTemplate")
    @ResponseBody
    public AjaxResult addToTemplate(String draftIds, int templateType) {
        String[] draftIdsArr;
        if (draftIds.contains(",")) {
            draftIdsArr = draftIds.split(",");
        } else {
            draftIdsArr = new String[]{draftIds};
        }
        for (int i = 0; i < draftIdsArr.length; i++) {
            try {
                wxOpenService.getWxOpenComponentService().addToTemplate(Integer.valueOf(draftIdsArr[i]), templateType);
            } catch (WxErrorException e) {
                return AjaxResult.error("上传代码【" + draftIdsArr[i] + "】时出错，请刷新后重试！");
            }
        }
        return AjaxResult.success();
    }

    @RequiresPermissions("back:wechatOpen:deleteTemplate")
    @PostMapping("/deleteTemplate")
    @ResponseBody
    public AjaxResult deleteTemplate(String ids) {
        String[] templateIdsArr;
        if (ids.contains(",")) {
            templateIdsArr = ids.split(",");
        } else {
            templateIdsArr = new String[]{ids};
        }
        for (int i = 0; i < templateIdsArr.length; i++) {
            try {
                wxOpenService.getWxOpenComponentService().deleteTemplate(Integer.valueOf(templateIdsArr[i]));
            } catch (WxErrorException e) {
                return AjaxResult.error("删除代码模板【" + templateIdsArr[i] + "】出错，请刷新后重试！");
            }
        }
        return AjaxResult.success();
    }
}
